package com.jeeplus.modules.api.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class PgwSignUtil {

	private static Logger logger = LoggerFactory.getLogger(PgwSignUtil.class);
	public static final String pri_sign = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDORgY8z8QssUlbSce8p9d4OA+yPYrjR5OIr9g9Z9HGybB7m2vgYxTiMIXpfc9EeWff0rb6olse0b1G9PPgImxQQEWFgSOSGR3T/CTkrn1Ygjki6RrgRXZBsszETr+rspVLAB2RXw7ssFL8W6FT29gEpng2eJymmOP+j5Xd1JKPyJgBqzco6EW1zPpJ7GNCnFXIxRIhQhC93p4sZaRS4Sb6wTHL1Shmk1LSzAdaoTFmJ+iG+yP4Wev6DUB51umtVrT4N5RD0rjMveobquoR5F1mSAwa4+oss2mp/yV5K4Fl+U9Q1Oze6Hsih6XezuEsvzBW6XN8KRINEaKPBEafeE2vAgMBAAECggEBAJF+TtQB8GtduVJMnjfxY0gGsvuT8S0SxXt6HNpjKlI+3N6y58pj2M0aULo65UF1KNF0/V+XuRHp+snb6VDEtwV78A2U4xQf5ywpA5TRhtQxNj/rj+t0007P4SLuML/YvPkj4bcyB4LndAFQWGCgBqRxDwXM2SGhYd+iQ6EuWRpUq4N03CrdwaYqYwLrLhV8Ap/V+yWhO7gLUyM6NClya5JMn9olp2zbBESI0Kmb/BbjeYSvmZPN9w/XOg5Mg9IWh/Lj0PZw4UYElMnYjlall+Eyn/IhNcIcAD8mJP0YORCX0HT/9Et3tt9sv53RVnfMKxLmJwbYw6IjOmK6rZ5lcoECgYEA+v3BSXfc7rK0A9oNDhExD8O9JbRZltu1B6l26vJxThr29Hr3kOpuiZcfKEVI+3DEEcppT0QR6dCktWvYOgBc3dsxqnB9+W0WBKY5IedGu3nlZ7ZqFcP8bInM03P4K5xQfNfR6YiLqK2t0V2KVjeWKgZvC+UBxQvp/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cg5a0VcuKHFuN6ph6PYyzBp/OTZldbM64uWp67sQ8NiX7UXsvjms0F1td4vmECQQD0YXkqLOwCphCAak4eiQU0KL7smSOlBB+R91UoWoIWJjSytkKpA+a/a+DWSXIgJzs0QYTcRXJyTPG4/PqwQLH5AkEA7PiNWpu8Tv4TNfl1WmDEqqEf9zMwjHXBVNmQ0rMYV6bb0UhPmiEXcHm6wLFJKl0nQ+QgSrJXmj2Rg5o0HP/PUwJAQ+F/YnOv6txt4P2mTV0KEP7waY/wEroeetEU2mypjbV3Fd0CjygCRFGW1m74QG4lR9KbMQQpUg6FZjj++U4/IQJBAMe0xHPK8YzkxM3k+Mh86uEdvvG2e0C0cIUQgeN/uZEM9w3N0gADyVwpyoBgKFgCf3fQxoINAJTlND/jce3KjC8CQAmYOFWUA0ySVRxRR2S5mYMVOtzj/jWvFOwlehYkfIKLwUeSTd95CPoqVV1dTZFYO1N4SKRTPD1F86FzkCjeemA=";//测试环境
	/**
	 * RSA签名
	 * 
	 * @param obj
	 * @return
	 */
	public static String genRSASign(String obj) {
		JSONObject reqObj = JSONObject.parseObject(obj);
		// // 生成待签名串
		String sign_src = genSignData(reqObj);
		logger.info("加签待签名原串:" + sign_src);
		//if (StringUtils.isBlank(sign_type) || "RSA".equals(sign_type)) {
		logger.info("RSA签名");
		return PgwTraderRSAUtil.sign(PgwSignUtil.pri_sign, sign_src);
	}

	/**
	 * 生成待签名串
	 * 
	 * @return
	 */
	private static String genSignData(JSONObject jsonObject) {
		StringBuffer content = new StringBuffer();
		// 按照key做首字母升序排列
		List<String> keys = new ArrayList<String>(jsonObject.keySet());
		Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			// sign 和ip_client 不参与签名
			if ("sign".equals(key)) {
				continue;
			}
			String value = (String) jsonObject.getString(key);
			// 空串不参与签名
			if (null == value) {
				continue;
			}
			if("data".equals(key)){
				JSONObject jsonData = JSONObject.parseObject(value);
				content.append((i == 0 ? "" : "&") + key + "={");
				content.append(genSignData(jsonData));
				content.append("}");
				continue;
			}
			content.append((i == 0 ? "" : "&") + key + "=" + value);

		}
		String signSrc = content.toString();
		if (signSrc.startsWith("&")) {
			signSrc = signSrc.replaceFirst("&", "");
		}
		return signSrc;
	}

	/**
	 * RSA签名 验证
	 * 
	 * @param obj
	 *            报文对象
	 * @param rsa_public
	 *            公钥
	 * @return
	 */
	public static boolean checkSignRSA(String obj, String rsa_public, String sign) {
		JSONObject reqObj = JSONObject.parseObject(obj);
		logger.info("RSA签名 验证 的参数 = " + obj);
		// 生成待签名串
		String sign_src = genSignData(reqObj);
		logger.info("验签待签名原串" + sign_src);
		logger.info("验签签名串" + sign);
		try {
			if (PgwTraderRSAUtil.checksign(rsa_public, sign_src, sign)) {
				logger.info("商户[" + reqObj.getString("mchtNo") + "]RSA签名验证通过");
				return true;
			} else {
				logger.info("商户[" + reqObj.getString("mchtNo") + "]RSA签名验证未通过");
				return false;
			}
		} catch (Exception e) {
			logger.info("商户[" + reqObj.getString("mchtNo") + "]RSA签名验证异常" + e.getMessage());
			return false;
		}
	}

}
